Individual Assignment

Write a program for a microcontroller development board that you made, to interact (with local input &/or output devices) and communicate (with remote wired or wireless devices)
Extra Credit: use different languages &/or development environments
Extra Credit: connect external components to the board

Group Assignment

Browse through the datasheet for your microcontroller
Compare the performance and development workflows for other architectures


Table of Contents



Week 6 Work Plan


This week starts by learning about embedded programming and how to program the XIAO-RP2040 development board, which was built in week 4. My instructor, recommended that we use Arduino IDE to program the XIAO microcontroller board. 

Seeed Studio XIAO RP2040

The Seeed Studio XIAO RP2040 is a microcontroller board based on the Raspberry Pi RP2040 chip. The Raspberry Pi RP2040 is a microcontroller designed by the Raspberry Pi Foundation, and it features a dual-core ARM Cortex-M0+ processor.

ItemValue
CPU Dual-core ARM Cortex M0+ processor up to 133MHz

Flash Memory2MB
SRAM 264KB
Digital I/O Pins11
Analog I/O Pins 4
PWM Pins11
I2C interface1
SPI interface1
UART interface 1
Power supply and downloading interfaceType-C
Power3.3V/5V DC

Dimensions 20×17.5×3.5mm
Programming LanguageArduino/Circuitpython/Micropython
📌
Follow the link below to download the datasheet for Seeed Studio XIAO RP2040.
https://files.seeedstudio.com/wiki/XIAO-RP2040/res/rp2040_datasheet.pdf
⬇️
The Youtube video mentioned below explains how to get started with the XIAO RP2040 board.
Getting Started with Seeed XIAO RP2040 Board with Projects | World Smallest Raspberry Pi Pico Board
Register and get $100 from NextPCB:
https://www.youtube.com/watch?v=iK155Fwf46U

XIAO-RP2040 Pinout Diagram

XIAO-RP2040 Schematic Diagram

Quentorres Development Board

The Quentorres Development Board was initially developed by Quentin Bolsée and later reimagined by Adrián Torres for the XIAO-RP2040 microcontroller.

📌
For more details click here.

Programming the XIAO-RP2040 Board

For programming the XIAO-Rp2040 board, I have tried to use multiple IDEs, such as:

Arduino IDE

The Arduino IDE (Integrated Development Environment) is used to write the computer code and upload this code to the physical board. The Arduino IDE is very simple and this simplicity is probably one of the main reason Arduino became so popular.

⬇️
Follow the link below to download the Arduino IDE.
Software
Open-source electronic prototyping platform enabling users to create interactive electronic objects.
https://www.arduino.cc/en/software
⬇️
Follow the link below to learn how to programme in the Arduino IDE.
Learn how to set up the Arduino Nicla Sense ME and get a quick overview of the components. Obtain information regarding pins and how to use the different sensors.
https://www.arduino.cc/en/Tutorial/HomePage

Local LED

LED Blink Algorithm

📜
Step 1: Start

Step 2: Set LED pin at 26 as output

Step 3: Turn on the LED for 1 second

Step 4: Turn off the LED for 1 second. Go to step 3.

LED Blink Flow Chart

LED Blink Code

const int led1=26;          //assigned pin 26 to the constant integer variable led1
    void setup() {
      pinMode(led1, OUTPUT);    // set the led1 as output
    }
    void loop() {
      digitalWrite(led1, HIGH); // set the led1 to on
      delay(1000);              // delayed to 1 second
      digitalWrite(led1, LOW); // set the led1 to off
      delay(1000);             // delayed  to 1 second
    }

Local Push Button

Push Button Based LED ON/OFF Algorithm

📜
Step 1: Start.

Step 2: Set the LED pins at 26, 0, and 1 as output.

Step 3: Set the button pin at 27 as input.

Step 4: Check the button state.

Step 5: If the button is pressed, turn on the LEDs. Go to step 4.

Step 6: If the button is released, turn off the LEDs. Go to step 4.

Push Button Based LED ON/OFF Flow Chart

Push Button Based LED ON/OFF Code 1

const int led1=26;            //assigned pin 26 to the constant integer variable led1
    const int led2=0;             //assigned pin 0 to the constant integer variable led2
    const int led3=1;             //assigned pin 1 to the constant integer variable led3
    const int but=27;             //assigned pin 27 to the constant integer variable but
    int buttonI=0;                //assigned value 0 to the integer variable buttonI //buttionI for button status
    void setup() {
      pinMode(led1, OUTPUT);     // set the led1 as output
      pinMode(led2, OUTPUT);     // set the led2 as output
      pinMode(led3, OUTPUT);     // set the led3 as output
      pinMode(but, INPUT);       // set the but as input
    }
    
    void loop() {
      buttonI = digitalRead(but);// read the button status
      if (buttonI==HIGH)
      {
        digitalWrite(led1, HIGH); // set the led1 on
        digitalWrite(led2, HIGH); // set the led2 on
        digitalWrite(led3, HIGH); // set the led3 on 
      }
      else
      {
        digitalWrite(led1, LOW); // set the led1 off 
        digitalWrite(led2, LOW); // set the led2 off 
        digitalWrite(led3, LOW); // set the led3 off 
      }
       
    }

Push Button Based LED ON/OFF Code 2

// Define the pin numbers for the LEDs and the button
    const int led1 = 26;    // Pin number for the first LED
    const int led2 = 0;     // Pin number for the second LED
    const int led3 = 1;     // Pin number for the third LED
    const int but = 27;     // Pin number for the button
    
    int buttonI = 0;        // Variable to store the button state
    
    void setup() {
      // Set the pinMode for each pin
      pinMode(led1, OUTPUT);   // Set the first LED pin as OUTPUT
      pinMode(led2, OUTPUT);   // Set the second LED pin as OUTPUT
      pinMode(led3, OUTPUT);   // Set the third LED pin as OUTPUT
      pinMode(but, INPUT);     // Set the button pin as INPUT
    }
    
    void loop() {
      buttonI = digitalRead(but); // Read the state of the button
      butfun(buttonI);// Call the function to handle button state
    }
    int butfun(int x) {
      if (x == HIGH) {
        // If the button state is HIGH (pressed), turn on all three LEDs
        digitalWrite(led1, HIGH);
        digitalWrite(led2, HIGH);
        digitalWrite(led3, HIGH);
      } else {
        // If the button state is LOW (not pressed), turn off all three LEDs
        digitalWrite(led1, LOW);
        digitalWrite(led2, LOW);
        digitalWrite(led3, LOW);
      }
      return 0; // Return 0 (this doesn't have a particular significance in this case)
    }

Algorithm for Push Button based LED ON/OFF

📜
Step 1: Start

Step 2: Set the LED pin at 26, 0, 1 as output, and set the button connected at pin 27 as input.

Step 3: Check the button state.

Step 4: Check the LED state.

Step 5: If the button is pressed and if the LEDs are off. Go to step 8.

Step 6: If the button is pressed and if the LEDs are on. Go to step 9.

Step 7: Go to step 3.

Step 8: Turn on the LEDs. Go to step 3.

Step 9: Turn off the LEDs. Go to step 3.

Push Button based LED ON/OFF Flow Chart

Push Button based LED ON/OFF Code using flag

const int led1 = 26; // Pin number for the first LED
    const int led2 = 0;  // Pin number for the second LED
    const int led3 = 1;  // Pin number for the third LED
    const int but = 27;  // Pin number for the push button
    int buttonI = 0;      // Variable to store the button state
    bool flag = false;    // Boolean flag to toggle the LEDs
    void setup() {
      pinMode(led1, OUTPUT); // Set the first LED pin as output
      pinMode(led2, OUTPUT); // Set the second LED pin as output
      pinMode(led3, OUTPUT); // Set the third LED pin as output
      pinMode(but, INPUT);   // Set the button pin as input
    }
    
    void loop() {
      buttonI = digitalRead(but); // Read the state of the button and store it in 'buttonI'
    
      if (buttonI == HIGH) {
        // If the button is pressed
        if (flag == false) {
          // If the flag is false, turn on all three LEDs
          flag = true;
          digitalWrite(led1, HIGH);
          digitalWrite(led2, HIGH);
          digitalWrite(led3, HIGH);
        } else {
          // If the flag is true, turn off all three LEDs
          flag = false;
          digitalWrite(led1, LOW);
          digitalWrite(led2, LOW);
          digitalWrite(led3, LOW);
        }
      }
    
      delay(300); // Introduce a delay to avoid rapid toggling and debounce the button
    }
const int led1=0;            // assigned pin 0 to integer variable led1 
    const int led2=1;            // assigned pin 1 to integer variable led2
    const int led3=26;           // assigned pin 26 to integer variable led3
    const int but=27;            // assigned integer variable but as 27. "but" for button
    int button_state=0;          // assigned 0 to integer variable button_state  
    int led_state=0;             // assigned 0 to integer variable "led_state"
    void setup() {
      pinMode(led1,OUTPUT);      // set the led1 as output
      pinMode(led2,OUTPUT);      // set the led2 as output
      pinMode(led3,OUTPUT);      // set the led3 as output
      pinMode(but,INPUT);        // set the but as input
    }
    void loop() {
      button_state= digitalRead(but); // read the digital value of but and stored to button_state
      
      if (button_state==1) // Check if the button is pressed
      {
        if (led_state==0) // Check if the led is off
        {
          digitalWrite(led1,HIGH); // Turn on led1 
          digitalWrite(led2,HIGH); // Turn on led2
          digitalWrite(led3,HIGH); // Turn on led3
          led_state=1;             // set the led status to on
        }
        else
        {
          digitalWrite(led1,LOW); //Turn off the led1
          digitalWrite(led2,LOW); //Turn off the led2
          digitalWrite(led3,LOW); //Turn off the led3
          led_state=0;            // set the led status to off
        }
      }
      delay(300);                 //delay is for debouncing
     }
⚠️
The above codes work great, but while testing, I found an issue. When the push button is pressed repeatedly, the LED starts to blink. My peers also had to deal with this issue. Our instructor, Mr. Saheen, explained the reason for the bounce of the switch and also explained how to solve it. 

Switch Debounce in Digital Circuits

⬇️
Follow the link below to learn more about debouncing.
Switch Debounce in Digital Circuits - GeeksforGeeks
A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.
https://www.geeksforgeeks.org/switch-debounce-in-digital-circuits/
⬇️
The Arduino button debounce YouTube video is linked below.
Arduino Button Debounce Tutorial
Arduino Button Tutorial: How to debounce a button on an Arduino Uno or Mega.
https://www.youtube.com/watch?v=jYOYgU2vlSE
⬇️
The following code fixed the led blinking issue when the push button was long-pressed:
const int led1 = 0;          // assigned pin 0 to integer variable led1
    const int led2 = 1;          // assigned pin 1 to integer variable led2
    const int led3 = 26;         // assigned pin 26 to integer variable led3
    const int but = 27;          // assigned integer variable but as 27. "but" for button
    int button_state = 0;        // assigned 0 to integer variable button_state
    int led_state = 0;           // assigned 0 to integer variable "led_state"
    bool pressed = false;        // assigned false to boolean variable pressed
    void setup() {
      pinMode(led1, OUTPUT);     // set the led1 as output
      pinMode(led2, OUTPUT);     // set the led2 as output
      pinMode(led3, OUTPUT);     // set the led3 as output
      pinMode(but, INPUT);       // set the but as input
    }
    void loop() {
      button_state = digitalRead(but); // read the digital value of but and stored to button_state
      if (button_state == HIGH)       // check if the button is pressed
      {
        if (pressed == false)         // check if pressed flag is false
        {
          if (button_state == 1)   // Check if the button is pressed
          {
            if (led_state == 0)        // Check if the led is off
            {
              digitalWrite(led1, HIGH); // Turn on led1
              digitalWrite(led2, HIGH); // Turn on led2
              digitalWrite(led3, HIGH); // Turn on led3
              led_state = 1;           // set the led status to on
            }
            else
            {
              digitalWrite(led1, LOW); //Turn off the led1
              digitalWrite(led2, LOW); //Turn off the led2
              digitalWrite(led3, LOW); //Turn off the led3
              led_state = 0;          // set the led status to off
            }
          }
          delay(300);                 //delay is for debouncing
          pressed = true;             //set the pressed flag as true
        }
      } else {
        pressed = false;             //set the pressed boolean as false
        delay(50);                   //set delay for 50 milli second
      }
    }

Serial Communication

Serial communication is a method of sending and receiving data between two or more electronic devices, one bit at a time over a single communication line.

The most common types of serial communication on Arduino are UART (Universal Asynchronous Receiver/Transmitter) and USB (Universal Serial Bus).

Here are the key components and aspects of serial communication in Arduino:

Serial.begin (baudrate):Initializes the serial communication with a specific baud rate (data transfer rate in bits per second).
Serial.print (data):Sends data (characters, numbers, etc.) to the serial port.
Serial.read():Reads incoming data from the serial port.
⬇️
Serial communication with Arduino The YouTube video is linked below.
Serial Communication with Arduino - The details!
Want to learn more? Check out our courses! ***We have no affiliation whatsoever with Arduino LLC, other than we think they are cool.***
https://www.youtube.com/watch?v=tpEo5AOSSkg
const int led1 = 0;          // assigned pin 0 to integer variable led1
    const int led2 = 1;          // assigned pin 1 to integer variable led2
    const int led3 = 26;         // assigned pin 26 to integer variable led3
    const int but = 27;          // assigned integer variable but as 27. "but" for button
    int button_state = 0;        // assigned 0 to integer variable button_state
    int led_state = 0;           // assigned 0 to integer variable "led_state"
    bool pressed = false;        // assigned false to boolean variable pressed
    void setup() {
      Serial.begin(9600);
      pinMode(led1, OUTPUT);     // set the led1 as output
      pinMode(led2, OUTPUT);     // set the led2 as output
      pinMode(led3, OUTPUT);     // set the led3 as output
      pinMode(but, INPUT);       // set the but as input
      Serial.print("week 06");
    }
    void loop() {
      button_state = digitalRead(but); // read the digital value of but and stored to button_state
      if (button_state == HIGH)       // check if the button is pressed
      {
        Serial.println("button pressed");
        if (pressed == false)         // check if pressed flag is false
        {
          if (button_state == 1)   // Check if the button is pressed
          {
            if (led_state == 0)        // Check if the led is off
            {
              Serial.println("LED is ON");
              digitalWrite(led1, HIGH); // Turn on led1
              digitalWrite(led2, HIGH); // Turn on led2
              digitalWrite(led3, HIGH); // Turn on led3
              led_state = 1;           // set the led status to on
            }
            else
            {
              Serial.println("LED is OFF");
              digitalWrite(led1, LOW); //Turn off the led1
              digitalWrite(led2, LOW); //Turn off the led2
              digitalWrite(led3, LOW); //Turn off the led3
              led_state = 0;          // set the led status to off
            }
          }
          delay(300);                 //delay is for debouncing
          pressed = true;             // assign the pressed flag to true
        }
      } else {
        pressed = false;              // set the pressed flag to false
        delay(50);                    // applied 50 milli second delay
      }
    }
    

Recursive Function

A recursive function is a function that calls itself during its execution. In other words, it's a function that solves a problem by solving smaller instances of the same problem. The process of solving a problem in terms of smaller instances is known as recursion.

For this time, I decided to use ChatGPT to code according to my desired output, and here is the prompt.

➡️
Prompt: Write a code for the xiao board to toggle 3 LEDs when the push button is pressed only one of the LEDs will turn and remain high until the push button is pressed again on using the recursive function.
const int buttonPin = 27;      // Pin number for the push button
    const int ledPins[] = {0, 1, 26};  // Pin numbers for three LEDs
    int currentLed = 0;            // Index of the currently lit LED
    int buttonState = LOW;         // Current state of the button
    int lastButtonState = LOW;     // Previous state of the button
    unsigned long lastDebounceTime = 0;  // Last time the button was pressed (milliseconds)
    unsigned long debounceDelay = 50;    // Delay time to debounce the button
    
    void setup() {
      for (int i = 0; i < 3; i++) {
        pinMode(ledPins[i], OUTPUT);   // Set LED pins as output
      }
      pinMode(buttonPin, INPUT);   // Set button pin as input
    }
    
    void loop() {
      int reading = digitalRead(buttonPin);  // Read the state of the button
    
      if (reading != lastButtonState) {
        lastDebounceTime = millis();  // Update debounce time when the button state changes
      }
    
      if ((millis() - lastDebounceTime) > debounceDelay) {
        if (reading != buttonState) {
          buttonState = reading;  // Update button state if debounced
          if (buttonState == HIGH) {
            toggleLED();  // Start the recursive LED toggle function
          }
        }
      }
    
      lastButtonState = reading;  // Save the current button state
    }
    
    void toggleLED() {
      digitalWrite(ledPins[currentLed], LOW);  // Turn off the current LED
    
      currentLed = (currentLed + 1) % 3;  // Move to the next LED index (circular increment)
    
      digitalWrite(ledPins[currentLed], HIGH);  // Turn on the new current LED
    }

Thonny Editor

Thonny is a free, open-source Python Integrated Development Environment (IDE). It's designed for beginners, with a basic user interface and Python 3 pre-installed. Thonny has a built-in debugger, step-by-step expression evaluation, and call stack visualization. It also helps users step into a function call by providing details about local variables and displaying the code pointer. Thonny is available on Windows, macOS, and Linux. It can be installed as a binary bundle with the latest Python interpreter, a pip-installable package, or the operating-system package manager on Debian, Raspberry Pi, Ubuntu, and Fedora.

⬇️
Follow the link below to install Thonny Editor.
Thonny, Python IDE for beginners
Thonny 4 is dedicated to Ukraine fighting the Russian invasion. 🇺🇦 Please support Ukraine! 🇺🇦
https://thonny.org/

Programming XIAO in MicroPython

The XIAO is a compact development board based on the ATSAMD21G18 microcontroller, and MicroPython is a lightweight implementation of Python 3 for microcontrollers.

MicroPython

MicroPython is a lean and efficient implementation of the Python 3 programming language that is designed to run on microcontrollers and constrained environments. It brings the ease and expressiveness of Python to the embedded systems world, making it more accessible for developers to work with microcontrollers and other resource-constrained devices.

MicroPython: An Intro to Programming Hardware in Python – Real Python
Are you interested in the Internet of Things, home automation, and connected devices? If so, then you're in luck! In this tutorial, you'll learn about MicroPython and the world of electronics hardware. You'll set up your board, write your code, and deploy a MicroPython project to your own device.
https://realpython.com/micropython/
📌
Click here to learn more about programming XIAO using MicroPython.

MicroPython RGB LED Code

# Import the WS2812 class from the ws2812 module
    from ws2812 import WS2812
    
    # Import the utime module for sleep functions and the machine module for hardware control
    import utime
    import machine
    
    # Set up a pin (pin 11) to control the power of the WS2812 LEDs
    power = machine.Pin(11, machine.Pin.OUT)
    power.value(1)  # Turn on the power to the WS2812 LEDs
    
    # Define RGB color values for convenience
    BLACK = (0, 0, 0)
    RED = (255, 0, 0)
    YELLOW = (255, 150, 0)
    GREEN = (0, 255, 0)
    CYAN = (0, 255, 255)
    BLUE = (0, 0, 255)
    PURPLE = (180, 0, 255)
    WHITE = (255, 255, 255)
    
    # Create a tuple of color values for iteration
    COLORS = (BLACK, RED, YELLOW, GREEN, CYAN, BLUE, PURPLE, WHITE)
    
    # Initialize the WS2812 object with pin 12 and 1 LED
    led = WS2812(12, 1)  # WS2812(pin_num, led_count)
    
    # Enter an infinite loop to continuously display colors
    while True:
        print("Beautiful color")
        
        # Iterate through each color in the COLORS tuple
        for color in COLORS:
            # Fill all LEDs with the current color
            led.pixels_fill(color)
            
            # Update the physical LEDs to display the filled color
            led.pixels_show()
            
            # Pause for a short duration to observe the color (0.2 seconds in this case)
            utime.sleep(0.2)

Mu Editor

Mu Editor is an open-source Python editor specifically designed for beginners and educators, especially those who are learning or teaching programming with the microcontroller platform CircuitPython. The editor is developed with simplicity in mind, providing an easy-to-use environment for writing, editing, and running Python code on microcontroller boards.

⬇️
Follow the link below to install Mu Editor.
Download Mu
The simplest and easiest way to get Mu is via the official installer for Windows or Mac OSX (we no longer support 32bit Windows). We also have an experimental AppImage for Linux users running on Intel based hardware.
https://codewith.mu/en/download

Programming XIAO in CircuitPython

CircuitPython is a programming language and a lightweight version of Python designed specifically for microcontrollers and small embedded systems. It is an open-source project developed by Adafruit Industries to make programming microcontrollers more accessible and user-friendly, especially for beginners and those new to electronics.

Welcome to CircuitPython!
New to CircuitPython? This is the place to start.
https://learn.adafruit.com/welcome-to-circuitpython/circuitpython-essentials
📌
Click here to learn more about programming XIAO using CircuitPython.

CircuitPython LED Blink Code

"""Example for Pico. Blinks the built-in LED."""
    import time
    import board
    import digitalio
    
    led = digitalio.DigitalInOut(board.LED)
    led.direction = digitalio.Direction.OUTPUT
    
    while True:
        led.value = True
        time.sleep(0.5)
        led.value = False
        time.sleep(0.5)

PlatformIo

PlatformIO is a free, open-source, multi-framework, cross-platform, cross-architecture, professional IDE tool. PlatformIO aims to simplify the process of building, testing, and deploying code for embedded systems and IoT devices.

Key features of PlatformIO include:

How to install PlatformIo in VS code

Programming XIAO-RP2040 using PlatformIo

⬇️
LED Blink code
#include <Arduino.h>
    
    const int ledPin = 0; // GPIO pin for the LED
    void setup() { 
      pinMode(ledPin, OUTPUT);      // Set the LED pin as an output
    }
    
    void loop() {
      digitalWrite(ledPin, HIGH); // set the led1 to on
      delay(1000);              // delayed to 1 second
      digitalWrite(ledPin, LOW); // set the led1 to off
      delay(1000); 
    }
⚠️
I have successfully built the code, but when I try to upload my code to the board, an error message occurs and it fails. The port was unable to be detected.

Final Result

External Components

⚠️
In order to connect external components to the QT development board, header pins need to be soldered to the board. Since the QT board is a single-sided PCB, we soldered on the top layer.
⬇️
Follow the link below to learn about PCB soldering.
Rayan Abdul Gafoor - Fab Academy
© 2024 Rayan Abdul Gafoor. All rights reserved. Students Agreement.
https://fabacademy.org/2024/labs/kochi/students/rayan-abdul/week04.html

Servo Motor

A servo motor, or servo, is an electronic device that rotates or pushes parts of a machine with precision. Servos are used to control the angular or linear position, velocity, and acceleration of a mechanical system.

Servo Motors, how do they work?
Servo motors explained, how do they work? Exclusive VPN offer from $1.98/m 👉 https://www.privateinternetaccess.com/TheEngineeringMindset
https://youtu.be/1WnGv-DPexc?si=k0_ni82EokoGcX_s

Here's a general overview of how a servo motor works:

  1. Motor:
    • The heart of the servo motor is a DC motor, often a brushed or brushless motor.
    • The motor provides the necessary rotational force to drive the output shaft.
  1. Position Sensor:
    • A position sensor, such as a potentiometer or an encoder, is typically attached to the output shaft of the motor.
    • The position sensor continuously measures the current position of the shaft.
  1. Control Circuit:
    • The control circuit is responsible for processing the input signals and comparing them with the actual position feedback from the position sensor.
    • It generates an error signal based on the difference between the desired position and the actual position.
  1. Amplifier:
    • The error signal is then amplified to produce a control signal with sufficient power to drive the motor.
  1. Gear Mechanism:
    • Many servo motors have a gear mechanism that reduces the speed of the motor and increases the torque at the output shaft. This helps in achieving higher precision.
  1. Output Shaft:
    • The output shaft of the servo motor rotates in response to the control signal applied by the amplifier.
    • As the output shaft rotates, it changes the position of the device or system it is controlling.
  1. Feedback Loop:
    • The position sensor continuously provides feedback to the control circuit.
    • The control circuit adjusts the control signal based on the feedback, reducing the error until the desired position is reached.
⬇️
The pinout diagram of the servo motors is shown below.

⬇️
The circuit cad between the servo motors and XIAO is shown below.
⬇️
Servo Motor Code
#include <Arduino.h>
    #include <Servo.h>
    
    Servo servoMotor; // Create a Servo object to control a servo motor
    
    void setup() {
      servoMotor.attach(2); // Attach the servo to GPIO pin 2
    }
    
    void loop() {
      servoMotor.write(180); // Set the servo position to 180 degrees
      delay(1000);          // Wait for 1 second
    
      servoMotor.write(90);  // Set the servo position to 90 degrees
      delay(1000);          // Wait for 1 second
    
      servoMotor.write(0);   // Set the servo position to 0 degrees
      delay(1000);          // Wait for 1 second
    }
⬇️
Final Result

HC-SR04 Ultrasonic Sensor

The HC-SR04 is an ultrasonic distance measuring sensor that uses sonar to measure non-contact distances. It's made up of two ultrasonic transducers: a transmitter that emits ultrasonic sound pulses and a receiver that listens for reflected waves. The sensor works by measuring the time it takes for the echo to return to calculate the distance to an object.

Using the HC-SR04 Ultrasonic Distance Sensor with Arduino - Everything you need to know!
Learn everything you need to know to use the HC-SR04 Ultrasonic Distance Sensor with an Arduino.
https://youtu.be/6F1B_N6LuKw?si=OTEbNqznQuxK502a

general overview of how the HC-SR04 ultrasonic sensor works:

  1. Ultrasonic Transmitter:
    • The sensor has an ultrasonic transmitter (also called a transducer) that emits short pulses of ultrasonic sound waves.
  1. Ultrasonic Receiver:
    • The sensor also has an ultrasonic receiver that detects the echo of the transmitted sound waves.
  1. Trigger Pulse:
    • To start the measurement process, a microcontroller or any control system sends a short pulse (typically 10 microseconds) to the trigger pin of the sensor.
  1. Ultrasonic Pulse Emission:
    • The HC-SR04 sensor emits a burst of ultrasonic waves (sound waves with a frequency above the human hearing range).
  1. Traveling to the Target:
    • The emitted ultrasonic waves travel through the air until they encounter an object.
  1. Reflection from the Object:
    • When the ultrasonic waves hit an object, they get reflected back towards the sensor.
  1. Echo Reception:
    • The ultrasonic receiver on the HC-SR04 detects the reflected waves as an echo.
  1. Time Measurement:
    • The time taken for the ultrasonic waves to travel to the object and back is measured. This time is often referred to as the "time of flight."
  1. Distance Calculation:
    • The distance (D) between the sensor and the object can be calculated using the formula: D = (Time of Flight * Speed of Sound) / 2
      • The speed of sound is approximately 343 meters per second (at room temperature).
  1. Output:
    • The HC-SR04 then provides the distance measurement as an output signal, typically in centimeters or inches.
⬇️
The pinout diagram of the ultrasonic sensor is shown below.

⬇️
The circuit cad between the ultrasonic sensor and XIAO is shown below.
⬇️
Ultrasonic sensor code
#include <Arduino.h>
    
    const int triggerPin = 4p; // GPIO pin for the ultrasonic sensor trigger
    const int echoPin = 3;    // GPIO pin for the ultrasonic sensor echo
    
    void setup() {
      Serial.begin(9600);
      pinMode(triggerPin, OUTPUT);
      pinMode(echoPin, INPUT);
    }
    
    void loop() {
      // Trigger ultrasonic sensor by sending a pulse
      digitalWrite(triggerPin, LOW);
      delayMicroseconds(2);
      digitalWrite(triggerPin, HIGH);
      delayMicroseconds(10);
      digitalWrite(triggerPin, LOW);
    
      // Measure the duration of the echo pulse
      unsigned long duration = pulseIn(echoPin, HIGH);
    
      // Calculate the distance in centimeters
      float distance = (duration * 0.0343) / 2;
    
      // Print the distance to the Serial Monitor
      Serial.print("Distance: ");
      Serial.print(distance);
      Serial.println(" cm");
    
      delay(1000); // Wait for a short duration before the next measurement
    }
⬇️
Final Result

HW-201 Infrared (IR) Sensor

The HW-201 is an infrared (IR) sensor module that can detect objects. It has a detection range of 2-30 cm, depending on the surface.

Components of an IR Sensor Module:

IR sensor Working Principle and Applications | Robu.in
Nowadays, Infrared technology has a wide variety of wireless applications mostly in object sensing & remote control. Know about IR sensor working principle
https://robu.in/ir-sensor-working/
⬇️
The pinout diagram of the IR sensor is illustrated below.
⬇️
The circuit cad between the IR sensor and XIAO is shown below.
⬇️
IR sensor code
#include <Arduino.h>
    
    const int irSensorPin = 3; // GPIO pin for the IR sensor
    
    void setup() {
      Serial.begin(9600);
      pinMode(irSensorPin, INPUT);
    }
    
    void loop() {
      // Read the digital signal from the IR sensor
      int irSensorValue = digitalRead(irSensorPin);
    
      // Check the digital signal and calculate distance
      if (irSensorValue == HIGH) {
        Serial.println("Object detected. Distance: Far");
      } else {
        Serial.println("No object detected. Distance: Near");
      }
    
      delay(1000); // Wait for a short duration before the next measurement
    }
⬇️
Final Result

Relay Module

A relay is an electromechanical switch that is operated by an electrical current. It consists of a coil and one or more sets of contacts. When an electrical current flows through the coil, it creates a magnetic field that activates the switch mechanism, allowing the contacts to open or close.

How Relays Work - Basic working principle electronics engineering electrician amp
How relays work. In this video we look at how relays work, what are relays used for, different types of relay, double pole, single pole, phototransistor, solid state relay, semiconductor, flywheel diodes, 8. Suppressor diodes, DPDT, Double Pole, Double Throw Relay, Double throw relay, single throw relay, latching relay, nc, normally closed relay, no, normally open relay, Electromagnetic, electromechanical relay.
https://youtu.be/n594CkrP6xE?si=AhGKtyoH0c5HMHT5
⬇️
The pinout diagram of the relay module is shown below.

⬇️
The circuit cad between the relay module and XIAO is shown below.

⬇️
Relay module code.
// Define the digital pin connected to the relay module
    const int relayPin = 3; 
    
    void setup() {
      // Set the relay pin as an OUTPUT
      pinMode(relayPin, OUTPUT);
    }
    
    void loop() {
      // Turn on the relay for 2 seconds
      digitalWrite(relayPin, HIGH);
      delay(2000);
    
      // Turn off the relay for 2 seconds
      digitalWrite(relayPin, LOW);
      delay(2000);
    }
⬇️
Final Result

Wired Communication

Joy Stick Module

A joystick module is a hardware component that provides a way to input control signals to electronic devices, typically used in applications such as gaming consoles, remote-controlled vehicles, and other interactive systems. It consists of a mechanism that allows users to move a lever or stick in various directions, and the module translates these movements into electrical signals that can be interpreted by a microcontroller or other electronic device.

Introduction to Dual Axis XY Joystick for Arduino
This video is Introduction to Dual Axis Joystick for Arduino with example.
https://www.youtube.com/watch?v=6N8Iq353GM8
⬇️
The pinout diagram of joystick module is shown below.
⬇️
The circuit cad between the joystick module and XIAO is shown below.

⬇️
Joystick module code
#include <Arduino.h>
    #include <Servo.h>
    // Define the digital pins for joystick button and X, Y directions
    const int buttonPin = 2; // Change this to the desired button pin
    const int xPin = 3;      // Change this to the desired X direction pin
    const int yPin = 4;      // Change this to the desired Y direction pin
    Servo servoMotor;
    void setup() {
      pinMode(buttonPin, INPUT_PULLUP); // Set the button pin as INPUT with internal pull-up resistor
      pinMode(xPin, INPUT);
      pinMode(yPin, INPUT);
      servoMotor.attach(1);
      Serial.begin(9600);
    }
    
    void loop() {
      // Read the state of the button
      int buttonState = digitalRead(buttonPin);
    
      // Read the digital values from the joystick
      int xValue = digitalRead(xPin);
      int yValue = digitalRead(yPin);
      if (xValue==0)
      {
        servoMotor.write(180);
      }
      if (yValue==0)
      {
        servoMotor.write(0);
      }
      if (buttonState==0)
      {
        servoMotor.write(45);
        delay(500);
        servoMotor.write(90);
    
      }
    
    
      // Print the values to the Serial Monitor
      Serial.print("Button State: ");
      Serial.print(buttonState);
      Serial.print("\tX: ");
      Serial.print(xValue);
      Serial.print("\tY: ");
      Serial.println(yValue);
    
      delay(500); // Adjust the delay based on your needs
    }
⬇️
Final Result

Wireless Communication

HC-05 Bluetooth Module

The HC-05 is a popular Bluetooth module commonly used for wireless communication in electronic projects. It is specifically designed for short-range wireless communication between electronic devices. The HC-05 is intended for short-range communication, typically up to 10 meters or 33 feet. This range may vary based on environmental factors.

How to Pair HC-05 Bluetooth Modules
A fast explanation on how to pair two HC-05 bluetooth modules!
https://youtu.be/BXXAcFOTnBo?si=zr2t9W6cKL8k72JR
⬇️
The pinout diagram of the HC-05 bluetooth module is shown below.
⬇️
The circuit cad between the bluetooth module and XIAO is shown below.

SoftwareSerial library

In Arduino IDE, the SoftwareSerial library allows you to create serial communication on any of the digital pins of your Arduino board. If you need additional serial ports or want to use pins other than the hardware serial pins (usually RX and TX), SoftwareSerial can be handy.

#include <Arduino.h>
    #include <SoftwareSerial.h>
    
    const int ledPin = 0; // GPIO pin for the LED
    SoftwareSerial bluetoothSerial(3, 4); // RX, TX pins for HC-05
    
    void setup() {
      Serial.begin(9600);          // Initialize the serial communication for debugging
      bluetoothSerial.begin(9600); // Initialize Bluetooth serial communication
      pinMode(ledPin, OUTPUT);      // Set the LED pin as an output
    }
    
    void loop() {
      if (bluetoothSerial.available() > 0) {
        char command = bluetoothSerial.read();
    
        // Toggle LED based on received command
        if (command == '1') {
          digitalWrite(ledPin, HIGH); // Turn on LED
          Serial.println("LED ON");
        } else if (command == '0') {
          digitalWrite(ledPin, LOW);  // Turn off LED
          Serial.println("LED OFF");
        }
      }
    }

Arduino BlueControl App

Arduino BlueControl app can be used to control your Arduino by sliders, buttons, and a joystick. Custom sliders and buttons can be used to interface with electronics components such as actuators and sensors connected to the Arduino.

⬇️
Final Result

Group Assignment Result

📌
For the group assignment page click here.

Reference

Resources and Downloads

📁 Blink Code

📁 Push Button Code 1

📁 Push Button Code 2

📁 Push Button Code 3

📁 Push Button Code 4

📁 Push Button Code 5

📁 Recursive Function Code

📁 Serial Communication

📁 Blink CircuitPython Code

📁 Blink MicroPython Code

📁 Servomotor Code

📁 Ultrasonic Sensor Code

📁 Relay Module Code

📁 IR Sensor Code

📁 Joystick Code

📁 Bluetooth Module Code